package com.sdk.pay.transfer.utils;

import android.annotation.SuppressLint;
import android.os.Environment;

import com.sdk.pay.transfer.BuildConfig;
import com.sdk.pay.transfer.constant.PayContext;

import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Joe on 2017/09/11 15:02.
 */

public class LogFileUtil {
    private static final ThreadLocal<SimpleDateFormat> sDateFormat = new ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("SimpleDateFormat")
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    public static void saveLogFile(String message) {
        message = stringNowTime() + " " + message + "\n";
        String fileName = "log_" + sDateFormat.get().format(new Date()) + ".log";
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + BuildConfig.APPLICATION_ID;
            File pathFile = new File(storagePath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            pathFile = new File(storagePath + File.separator + PayContext.LOG_DIR_NAME);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            File file1 = new File(pathFile, fileName);
            FileWriter fileWriter1 = null;
            try {
                fileWriter1 = new FileWriter(file1, true);
                fileWriter1.write(message);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                quietClose(fileWriter1);
            }
        }
    }

    private static void quietClose(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String stringNowTime() {
        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(new Date());
    }
}
